package com.yjf.ljr.activity;

import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.RegisterSubmitDataClass;
import com.yjf.ljr.dataclass.RegisterTokenDataClass;
import com.yjf.ljr.dataclass.SendSmsCodeClass;
import com.yjf.ljr.dataclass.SendSmsCodeDataClass;
import com.yjf.ljr.dataclass.VerifyRefereesDataClass;
import com.yjf.ljr.dataclass.VerifyUserDataClass;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AESUtil;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.util.Base64;
import com.yjf.ljr.util.SPreferences;
import com.yjf.ljr.view.RedPacketDialog;

public class RegistrationActivity extends IjActivity implements OnClickListener {

	@ID("etUserName")
	private EditText mEtUserName;// 用户名
	// @ID("etRealName")
	// private EditText mEtRealName;// 真实姓名
	@ID("etCommonEmail")
	private EditText mEtCommonEmail;// 常用邮箱
	@ID("etPwd")
	private EditText mEtPwd;// 登录密码
	@ID("etCommonPhone")
	private EditText mEtCommonPhone;// 常用手机号
	@ID("etVerifyCode")
	private EditText mEtVerifyCode; // 验证码
	@ID("etReferees")
	private EditText mEtReferees; // 推荐人编号

	@ID("btnGetVerifyCode")
	private Button mBtntnGetVerifyCode;
	@ID("btregister_next")
	private Button mBtnRegisterNext;
	@ID("tv_title_btn_left")
	private TextView mTvTitleBtnLeft;
	// public static RegistrationActivity instance;

	private String mStrToken;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			int time = (Integer) msg.obj;
			mBtntnGetVerifyCode.setText(" （" + String.format("%02d秒", time) + "） ");
			if (time-- > 0) {
				mHandler.sendMessageDelayed(mHandler.obtainMessage(0, time), 1000);
			} else {
				mBtntnGetVerifyCode.setBackgroundResource(R.drawable.btn_light_gray_4corners);
				mBtntnGetVerifyCode.setClickable(true);
				mBtntnGetVerifyCode.setText(" 重新获取 ");
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_registration);
		initControl();
	}

	@Override
	protected void onResume() {
		showProgressDialog();
		new GetTokeTask().execute();
		super.onResume();
	}

	private void initControl() {
		setLeftBtnClick();
		// setLeftBtnTitle("返回");
		// instance = this;
		setTitleStr("用户注册");
		mBtntnGetVerifyCode.setOnClickListener(this);
		mBtnRegisterNext.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btregister_next:

			String userName = mEtUserName.getText().toString().trim();
			if (TextUtils.isEmpty(userName)) {
				showToast("请输入用户名");
				return;
			}
			if (isChinese(userName)) {
				showToast("用户名不能包含中文");
				return;
			}
			if (userName.length() < 6 || userName.length() > 16) {
				showToast("用户名长度6-16个字符");
				return;
			}

			String email = mEtCommonEmail.getText().toString().trim();
			if (TextUtils.isEmpty(email)) {
				showToast("请输入常用邮箱");
				return;
			}
			if (!isEmail(email)) {
				showToast("邮箱地址格式不符");
				return;
			}

			String pwd = mEtPwd.getText().toString().trim();
			if (TextUtils.isEmpty(pwd)) {
				showToast("请输入登录密码");
				return;
			}
			if (isChinese(pwd)) {
				showToast("密码不能包含中文");
				return;
			}
			if (pwd.length() < 6 || pwd.length() > 20) {
				showToast("密码长度不符");
				return;
			}
			if (AppUtil.isNumeric(pwd)) {
				showToast("密码不能全为数字");
				return;
			}
			// if (AppUtil.isCharAllSame(pwd)) {
			// showToast("密码不能使用完全相同的数字、字母或符号");
			// return;
			// }
			if (!AppUtil.hasDigit(pwd)) {
				showToast("密码不能全为字母");
				return;
			}
			String mobile = mEtCommonPhone.getText().toString().trim();
			if (TextUtils.isEmpty(mobile)) {
				showToast("请输入手机号码");
				return;
			}
			if (!isMobileNO(mobile)) {
				showToast("手机号码格式不符");
				return;
			}

			String verifyCode = mEtVerifyCode.getText().toString().trim();
			if (TextUtils.isEmpty(verifyCode)) {
				showToast("请输入验证码");
				return;
			}

			if (TextUtils.isEmpty(mStrToken)) {
				return;
			}
			showProgressDialog();
			if (TextUtils.isEmpty(mEtReferees.getText().toString().trim())) {

				new VerifyUserTask(userName, email, AESUtil.encode(pwd), mobile, verifyCode, mEtReferees
						.getText().toString().trim()).execute();
			} else {
				new VerifyRefereesTask(userName, email, AESUtil.encode(pwd), mobile, verifyCode, mEtReferees
						.getText().toString().trim()).execute();
			}

			break;
		case R.id.btnGetVerifyCode:
			String phoneNum = mEtCommonPhone.getText().toString().trim();
			if (TextUtils.isEmpty(phoneNum)) {
				showToast("请输入手机号码");
				return;
			}
			if (!isMobileNO(phoneNum)) {
				showToast("手机号码格式不符");
				return;
			}
			showProgressDialog();
			new SendSmsCodeTask(phoneNum).execute();

			mBtntnGetVerifyCode.setBackgroundResource(R.drawable.shape_btn_gray_bg);
			mBtntnGetVerifyCode.setClickable(false);
			mHandler.sendMessageDelayed(mHandler.obtainMessage(0, 60), 0);
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CommonData.REQUEST_CODE_LOGIN:
				setResult(RESULT_OK);
				finish();
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	class GetTokeTask extends AsyncTask<Void, Void, String> {

		private RegisterTokenDataClass dc = new RegisterTokenDataClass();

		@Override
		protected String doInBackground(Void... arg0) {
			RequestObject requestObject = new RequestObject();
			requestObject.method = "toRegisterPage";
			return requestDataAndGetErrorMsg(requestObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				mStrToken = dc.token;
			}
			dismissProgressDialog();
		}
	}

	class SendSmsCodeTask extends AsyncTask<Void, Void, String> {

		private String mobile;// 电话号码
		private SendSmsCodeDataClass dc = new SendSmsCodeDataClass();

		public SendSmsCodeTask(String mobile) {
			this.mobile = mobile;
		}

		@Override
		protected String doInBackground(Void... arg0) {
			RequestObject requestObject = new RequestObject();
			requestObject.method = "sendSmsCode";
			requestObject.map.put("mobile", mobile);
			requestObject.map.put("business", "register");
			return requestDataAndGetErrorMsg(requestObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				if ("1".equals(dc.code)) {
					showToast("验证码已发送，请注意查收");
				}
			}
			dismissProgressDialog();
		}
	}

	/** 验证经纪人账户 **/
	class VerifyRefereesTask extends AsyncTask<Void, Void, String> {
		VerifyRefereesDataClass dc = new VerifyRefereesDataClass();
		private String userName;
		private String email;
		private String pwd;
		private String mobile;
		private String verifyCode;
		private String referees;

		public VerifyRefereesTask(String userName, String email, String pwd, String mobile, String verifyCode,
				String referees) {
			this.referees = referees;
			this.userName = userName;
			this.email = email;
			this.pwd = pwd;
			this.mobile = mobile;
			this.verifyCode = verifyCode;
			this.referees = referees;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			RequestObject requestObject = new RequestObject();
			requestObject.method = "verifyReferees";
			requestObject.map.put("referees", referees);
			return requestDataAndGetErrorMsg(requestObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			if (!(TextUtils.isEmpty(result))) {
				// showToast(result);
				dismissProgressDialog();
				showToast(result);
			} else {
				new VerifyUserTask(userName, email, pwd, mobile, verifyCode, referees).execute();
			}

		}
	}

	class RegisterSubmitTask extends AsyncTask<Void, Void, String> {
		private String userName;
		private String mail;
		private String pwd;
		private String verifyCode;
		private String mobile;
		private String referees;
		RegisterSubmitDataClass dc = new RegisterSubmitDataClass();

		public RegisterSubmitTask(String userName, String mail, String pwd, String mobile, String verifyCode,
				String referees) {
			this.userName = userName;
			this.mail = mail;
			this.pwd = pwd;
			this.verifyCode = verifyCode;
			this.mobile = mobile;
			this.referees = referees;

		}

		@Override
		protected String doInBackground(Void... arg0) {
			RequestObject requestObject = new RequestObject();
			requestObject.method = "registerSubmit";
			requestObject.map.put("userName", userName);
			requestObject.map.put("mail", mail);
			String pwdStr = URLEncoder.encode(pwd);
			requestObject.map.put("logPassword", pwdStr);
			requestObject.map.put("mobile", mobile);
			requestObject.map.put("code", verifyCode);
			requestObject.map.put("token", mStrToken);
			requestObject.map.put("referees", referees);
			return requestDataAndGetErrorMsg(requestObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			dismissProgressDialog();
			if (!(TextUtils.isEmpty(result))) {
				// showToast(result);
				showToast(result);
			} else {

				if (dc.giftMoney != null && "1".equals(dc.giftMoney)) {
					showRedPacketDialog(dc);
					return;
				}
				Intent intent = new Intent(RegistrationActivity.this,RegistrationActiveActivity.class);
				String mobile = mEtCommonPhone.getText().toString().trim();
				intent.putExtra("phoneNum", mobile);
				startActivityForResult(intent, CommonData.REQUEST_CODE_LOGIN);
				SPreferences.setUserName(RegistrationActivity.this, userName);
			}
		}

		public void showRedPacketDialog(final RegisterSubmitDataClass dc) {
			RedPacketDialog redPacketDialog = new RedPacketDialog(RegistrationActivity.this);
			redPacketDialog.setRedPacketMessage(dc.giftMoneyMessage);
			redPacketDialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					Intent intent = new Intent(RegistrationActivity.this,RegistrationActiveActivity.class);
					String mobile = mEtCommonPhone.getText().toString().trim();
					intent.putExtra("phoneNum", mobile);
					startActivityForResult(intent, CommonData.REQUEST_CODE_LOGIN);
					SPreferences.setUserName(RegistrationActivity.this, userName);					
				}
			});
			redPacketDialog.show();
		}
	}

	// 判断phone格式是否正确
	public boolean isMobileNO(String mobiles) {
		// Pattern p =
		// Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	// 判断email格式是否正确
	public boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);

		return m.matches();
	}

	// 判断是不是中文
	public boolean isChinese(String name) {
		String str = "^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$";

		boolean isIncludeChinese = false;
		for (int i = 0; i < name.length(); i++) {
			if (Pattern.matches(str, name.substring(i, i + 1))) {
				isIncludeChinese = true;
				break;
			}
		}
		return isIncludeChinese;

		// Pattern p = Pattern.compile(str);
		// Matcher m = p.matcher(name);
		// return m.matches();
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		return false;
	}

	class VerifyUserTask extends AsyncTask<Void, Void, String> {
		private String userName;
		private String email;
		private String pwd;
		private String mobile;
		private String verifyCode;
		private String referees;
		VerifyUserDataClass dc = new VerifyUserDataClass();

		public VerifyUserTask(String userName, String email, String pwd, String mobile, String verifyCode,
				String referees) {
			this.userName = userName;
			this.email = email;
			this.pwd = pwd;
			this.mobile = mobile;
			this.referees = referees;
			this.verifyCode = verifyCode;
		}

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			RequestObject mObject = new RequestObject();
			mObject.method = "verifyUser";
			mObject.map.put("userName", userName);
			return requestDataAndGetErrorMsg(mObject, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (!TextUtils.isEmpty(result)) {// fail
				showToast(result);
				dismissProgressDialog();
			} else {// success
				new RegisterSubmitTask(userName, email, pwd, mobile, verifyCode, referees).execute();
			}

		}

	}
}
